package com.zhanghe.study.thread;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zh
 * @date 2021/12/1 15:11
 */
public class TestUnsafe {
    static final Unsafe unsafe;

    static final long valueOffset;

    private volatile int value = 0;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);

            unsafe = (Unsafe) theUnsafe.get(null);

            valueOffset = unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("value"));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("");
        }

    }

    public static void main(String[] args) {
        TestUnsafe testUnsafe = new TestUnsafe();

        unsafe.getAndAddInt(testUnsafe, valueOffset, 1);
        System.out.println(testUnsafe.value);
    }
}
